﻿using WLYT.Application.Interfaces;
using WLYT.Common;
using WLYT.Core;
using WLYT.Domain.Entries;
using WLYT.Domain.Model;
using WLYT.Redis;

namespace WLYT.Application.Services
{
    public class AuthService(IRepository<Sys_User> userRepository,
                             IRepository<Sys_Role> roleRepository,
                             IRepository<Sys_Operation> sysOperationRepository) : IAuthService
    {
        public async Task<LoginResult> Login(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("请输入用户名或密码！");
            }
            LoginResult rs = new LoginResult();
            Data data = new Data();
            string md5Pwd = HashHelper.Md5(password);
            Sys_User user = await userRepository.GetFirstAsync(e => e.UserNo == userName && e.Password == md5Pwd);
            if (user != null)
            {
                try
                {
                    int expireMinutes = AppConfig.TokenAuthConfig.AccessExpiration;
                    data.Token = JwtHelper.CreateToken(user);
                    data.User = user;
                    data.ExpireAt = DateTime.Now.AddMinutes(expireMinutes);
                    data.Permissions = await GetOperation(user.RoleId);
                    rs.Message = "登陆成功";
                    rs.Success = true;
                    rs.Data = data;
                }
                catch (Exception ex)
                {
                    rs.Message = ex.Message;
                    rs.Success = false;
                }
            }
            else
            {
                rs.Message = "账户或密码错误";
                rs.Success = false;
            }
            return rs;
        }

        private async Task<Permission[]> GetOperation(int roleId)
        {
            var role = await roleRepository.GetByIdAsync(roleId);
            List<string> roles = role.Permission.Split(',').ToList();

            IList<Sys_Operation> operationList = new List<Sys_Operation>();
            if (!roles.Any(item => item == "*"))
            {
                IList<string> operations = roles.Where(p => p.Contains("_")).ToList();
                foreach (var item in operations)
                {
                    operationList.Add(new Sys_Operation
                    {
                        Code = item.Split('_').LastOrDefault(),
                        MenuUrl = item.Split('_').FirstOrDefault(),
                    });
                }
            }
            else
            {
                operationList = await sysOperationRepository.GetListAsync();
            }
            return operationList.GroupBy(p => p.MenuUrl).Select(p => new Permission { Id = p.Key, Operation = p.Select(q => q.Code).ToArray() }).ToArray();
        }
    }
}
